import 'dart:convert';
import 'dart:ui';
import 'package:ladder_cash/Global.dart';
import 'package:ladder_cash/app/com/service/reported_data_service.dart';
import 'package:ladder_cash/app/com/view/address_select.dart';
import 'package:ladder_cash/app/app.dart';
import 'package:ladder_cash/app/com/http/http_request.dart';
import 'package:ladder_cash/app/com/service/burial_point_service.dart';
import 'package:ladder_cash/app/com/service/information_service.dart';
import 'package:ladder_cash/app/com/view/flutter_pickers_master/time_picker/model/date_mode.dart';
import 'package:ladder_cash/app/com/view/flutter_pickers_master/time_picker/model/pduration.dart';
import 'package:ladder_cash/app/com/view/my_date_picker.dart';
import 'package:ladder_cash/app/com/view/webview/my_web/my_web_page.dart';
import 'package:ladder_cash/app/comm_key_def.dart';
import 'package:ladder_cash/app/key_mix.dart';
import 'package:ladder_cash/app/page/component/common.dart';
import 'package:ladder_cash/app/page/component/decoration_bg.dart';
import 'package:ladder_cash/config/super_theme.dart';
import 'package:ladder_cash/generated/assets.dart' as myAssets;
import 'package:ladder_cash/value/app_colors.dart';
import 'package:ladder_cash/value/app_lstyle.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:liuxlcommon/util/string_utils.dart';
import 'package:liuxlcommon/util/toast_util.dart';
import 'package:liuxlcommon/view/lxl_widget.dart';
import 'package:liuxlcommon/view/my_box.dart';
import 'package:liuxlcommon/view/my_style.dart';

import '../../../gen/assets.gen.dart';
import '../../../generated/l10n.dart';
import '../../../library/src/logger.dart';

class AuthenticationLogic extends GetxController {
  ///产品id
  late String product_id;
  int steepIndex = 0;
  String steepKey = "";
  String title = "";
  Map? productData;
  Map? authenticationInfo;
  bool isCompleteAll = false;
  bool isBack = false;
  InformationService informationService = InformationService();

  late BuildContext context;
  int bankType = 1;

  @override
  void onInit() {
    super.onInit();
    try {
      product_id = Get.arguments['product_id'];
      isBack = Get.arguments['isBack'];
    } catch (e) {
      ToastUtils.toast(e);
      Get.back();
    }
    try {
      productData = Get.arguments['productData'];
      setStatus();
      // ignore: empty_catches
    } catch (e) {}
  }

  getProductData() async {
    productData = await HttpRequest()
        .post('/v3/product/detail'.hx, {'product_id'.hx: product_id});
    setStatus();
    return productData;
  }

  setStatus() {
    if (productData != null) {
      String next = productData?['nextStep'.hx]?['taskType'.hx] ?? "";
      steepKey = next;
      Logger.d(steepKey);
      List lists = [
        "agonies",
        CommKeyDef.public,
        CommKeyDef.personal,
        CommKeyDef.job,
        CommKeyDef.ext,
        CommKeyDef.bank
      ];
      if (next.isEmpty) {
        //认证完成
        return;
      }
      title = productData?['nextStep'.hx]?['title'.hx];
      steepIndex = lists.indexOf(next);
    }
    if (StringUtils.isEmpty(steepKey)) Get.back();
    //
    // if (steepKey == CommKeyDef.bank) {
    //   Future.delayed(const Duration(milliseconds: 300), () {
    //     Get.off(
    //         MyWebPage(
    //             url: "${HttpRequest.host}/grease",
    //             arguments: {'product_id'.hx: product_id}),
    //         transition: Transition.noTransition);
    //   });
    //   return;
    // }
  }

  ///获取用户身份信息（第一项）
  getIdInfo() async {
    productData ??= await getProductData();
    isCompleteAll = false;
    authenticationInfo =
        await HttpRequest().post('/v3/certify/basic-person-info'.hx, {
      'product_id'.hx: product_id,
      'mobilePhone'.hx: App.userInfoModel.username,
      'mobile'.hx: App.userInfoModel.username
    });
    if (authenticationInfo?['id_front'.hx]['status'.hx] == 1 &&
        authenticationInfo?['liveness'.hx]['status'.hx] == 1) {
      isCompleteAll = true;
    }

    // if (StringUtils.isNotEmpty(authenticationInfo?['item'.hx]['face_recognition_picture'.hx]) &&
    //     StringUtils.isNotEmpty(authenticationInfo?['item'.hx]['id_number_z_picture'.hx])) {
    //   isCompleteAll = true;
    // }

    return authenticationInfo;
  }

  getUserInfo() async {
    productData ??= await getProductData();
    isCompleteAll = true;
    authenticationInfo = await HttpRequest().post(
        '/v3/certify/personal-info'.hx,
        {'product_id'.hx: product_id, 'mobile'.hx: App.userInfoModel.username});

    return authenticationInfo;
  }

  ///获取用户信息
  getQuestionnaireSurveyInfo() async {
    productData ??= await getProductData();
    isCompleteAll = true;
    authenticationInfo = await HttpRequest().post('/v3/certify/credit-info'.hx,
        {'product_id'.hx: product_id, 'mobile'.hx: App.userInfoModel.username});
    return authenticationInfo;
  }

  ///得到个人信息
  getJobInfo() async {
    productData ??= await getProductData();
    isCompleteAll = true;
    authenticationInfo = await HttpRequest().post('/v3/certify/job-info'.hx,
        {'product_id'.hx: product_id, 'mobile'.hx: App.userInfoModel.username});
    return authenticationInfo;
  }

  getContactInfo() async {
    productData ??= await getProductData();
    isCompleteAll = true;
    authenticationInfo = await HttpRequest().post('/v3/certify/ext-info-new'.hx,
        {'product_id'.hx: product_id, 'mobile'.hx: App.userInfoModel.username});
    return authenticationInfo;
  }

  getParams() {
    Map<String, dynamic> params = {};
    for (Map item in authenticationInfo!['items'.hx]) {
      if (item['cate'.hx] == CommKeyDef.txt ||
          item['cate'.hx] == CommKeyDef.citySelect ||
          item['cate'.hx] == CommKeyDef.day) {
        params[item['code'.hx]] = item['value'.hx];
      } else if (item['cate'.hx] == CommKeyDef.enum1) {
        Map keyMap = {};
        for (dynamic d in item['note'.hx]) {
          keyMap[d['name'.hx].toString().trim()] = d['type'.hx];
        }
        params[item['code'.hx]] = keyMap[item['value'.hx].toString().trim()];
      }
    }
    params['product_id'.hx] = product_id;
    return params;
  }

  saveQuestionnaireSurvey() async {
    if (await informationService.saveQuestionnaireSurvey(getParams())) {
      BurialPointService.end(BPoint.questionnaire);
      saveNext();
    }
  }

  saveUserInfo() async {
    if (await informationService.saveUserInfo(getParams())) {
      BurialPointService.end(BPoint.personage);

      saveNext();
    }
  }

  ///保存
  saveJopInfo() async {
    if (await informationService.saveJobInfo(getParams())) {
      BurialPointService.end(BPoint.job);
      saveNext();
    }
  }

  ///保存
  saveContactInfo() async {
    List<Map<String, dynamic>> listparams = [];
    for (Map item in authenticationInfo!['emergent'.hx]) {
      Map<String, dynamic> params = {};
      params['relation'.hx] = item['relation'.hx];
      params['name'.hx] = item['name'.hx];
      params['mobile'.hx] = item['mobile'.hx];
      listparams.add(params);
    }
    if (await informationService.saveContactInfo(
        {'data'.hx: json.encode(listparams), 'product_id'.hx: product_id})) {
      BurialPointService.end(BPoint.contact);

      saveNext();
    }
  }

  getBankInfo() async {
    productData ??= await getProductData();
    isCompleteAll = true;
    authenticationInfo = await HttpRequest().post('/v3/bind-card/card-init'.hx,
        {'product_id'.hx: product_id, 'mobile'.hx: App.userInfoModel.username});
    return authenticationInfo;
  }

  saveBankInfo() async {
    if (await informationService.saveBankInfo(getParams())) {
      BurialPointService.end(BPoint.bank);
      Get.back();
    }
  }

  ///保存
  saveNext() async {
    ReportedDataService().reportLocationInfo();
    if (isBack) {
      Get.back();
      return;
    }
    productData = null;
    authenticationInfo = null;
    update();
  }

  itemTip(item) {
    return [
      LSizeBoxHeight(15.w),
      LText(item['title'.hx], lStyle: itemTitleSty),
      LSizeBoxHeight(7.w)
    ];
  }

  Widget itemInput(index, item) {
    String title = item['title'.hx];
    return LColumn.eazy([
      LText(title, lStyle: itemTitleSty),
      10.lsh,
      LRow.eazy([
        LInput(item['value'.hx],
            lStyle: inputSty..hintText = item['subtitle'.hx],
            lInputType: item['inputType'.hx] == 1
                ? LInputType.INT
                : LInputType.TEXT, onChanged: (txt) {
          authenticationInfo!['items'.hx][index]['value'.hx] = txt;
          item['value'.hx] = txt;
        }),
      ]).css(inputBoxCss),
      LDivider(1.w, const Color(0xFFEAEAEA))
    ]);
  }

  // 调查单选
  itemSingleSelection(item, String type) {
    if (item['cardTypeMi'] != null) {
      if (item['cardTypeMi'] != 0 && item['cardTypeMi'] != bankType) {
        return const [SizedBox()];
      }
    }
    String title = item['title'.hx];
    List<String> lists = [];
    for (dynamic d in item['note'.hx]) {
      var strs = d['name'.hx];
      lists.add(strs);

      try {
        if (item['value'.hx] is String) {
          if (item['value'.hx].length == item['value'.hx].trim().length) {
            // item['value'] = int.parse(item['value']);
            item['value'.hx] = item['value'.hx].trim();
          }
        }
      } catch (e) {}

      if (item['value'.hx] is int) {
        int key = item['value'.hx];
        item['value'.hx] = "";
        for (dynamic im in item['note'.hx]) {
          if (key == im['type'.hx]) {
            if (item['code'.hx] == "bankType") {
              bankType = im['type'.hx];
            }

            String v = im['name'.hx];
            item['value'.hx] = " $v ";
            break;
          }
        }
      }
    }
    if (type == CommKeyDef.credit) {
      return Container(
        decoration: getBorderDecoration(),
        padding: EdgeInsets.all(12.w),
        child: Column(
          children: [
            middleFont(title, fontsize: 16),
            ...lists.map((ele) {
              return InkWell(
                onTap: () {
                  item['value'.hx] = " $ele ";
                  update();
                },
                child: Container(
                  margin: EdgeInsets.only(top: 12.sp),
                  padding: EdgeInsets.symmetric(horizontal: 12.w),
                  height: 42.w,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8), // 圆角半径为 20 像素
                      border: Border.all(
                        color: Colors.black, // 边框颜色为黑色
                        width: 2, // 边框宽度为 2 像素
                      ),
                      color: item['value'.hx] == " $ele "
                          ? SuperTheme.inputBgPrimary
                          : Colors.white),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(ele),
                      Image.asset(
                        item['value'.hx] == " $ele "
                            ? Assets.login.checked.path
                            : Assets.login.check.path,
                        width: 16.w,
                        height: 16.w,
                      )
                    ],
                  ),
                ),
              );
            })
          ],
        ),
      );
    } else {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          middleFont(title, fontsize: 16),
          InkWell(
            onTap: () {
              MyDatePicker.showSinglePicker(context,
                  title: title,
                  data: lists,
                  selectData: item['value'.hx].trim(), onConfirm: (txt, i) {
                item['value'.hx] = " $txt ";
                if (item['code'.hx] == "bankType") {
                  bankType = item['note'.hx][i]['type'.hx];
                }
                update();
              });
            },
            child: Container(
              margin: EdgeInsets.only(top: 12.sp),
              padding: EdgeInsets.symmetric(horizontal: 12.w),
              height: 42.w,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8), // 圆角半径为 20 像素
                color: SuperTheme.greyF7,
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    StringUtils.isNotEmpty(item['value'.hx])
                        ? item['value'.hx]
                        : S.current.pleaseSelect,
                    style: TextStyle(
                        color: StringUtils.isEmpty(item['value'.hx])
                            ? SuperTheme.grey99
                            : Colors.black),
                  ),
                  Icon(
                    Icons.arrow_forward_ios_rounded,
                    size: 18,
                    color: SuperTheme.grey99,
                  )
                ],
              ),
            ),
          )
        ],
      );
    }
  }

  itemDate(item) {
    String title = item['title'.hx];

    return LStack([
      LColumn.eazy([
        LText(title, lStyle: itemTitleSty),
        LRow.eazy([
          LText(StringUtils.defaultValue(item['value'.hx], item['subtitle'.hx]),
              lStyle: inputSty
                ..color = StringUtils.isNotEmpty(item['value'.hx])
                    ? Colors.black
                    : AppColors.textSecondColor, onTap: () {
            MyDatePicker().showDatePicker(context,
                onConfirm: (txt, PDuration p) {
              item['value'.hx] = txt;
              update();
            }, model: DateMode.YMD, selectTxt: item['value'.hx]);
          }),
          LImage.easy(myAssets.Assets.molopNewArrowdown, 7.w, 12.w)
        ]).css(inputBoxCss),
        LDivider(1.w, const Color(0xFFEAEAEA))
      ])
    ]);
  }

  itemAddress(item) {
    String title = item['title'.hx];

    return LStack([
      LColumn.eazy([
        LText(title, lStyle: itemTitleSty),
        LRow.eazy([
          LText(StringUtils.defaultValue(item['value'.hx], item['subtitle'.hx]),
              lStyle: inputSty
                ..color = StringUtils.isNotEmpty(item['value'.hx])
                    ? Colors.black
                    : AppColors.textSecondColor, onTap: () {
            AddressSelectDialog().show(
                title: title,
                call: (t) {
                  item['value'.hx] = t;
                  update();
                  Future.delayed(Duration(milliseconds: 100)).then((v) {
                    OldLInput.unfocus();
                  });
                });
          }),
          LImage.easy(myAssets.Assets.molopNewArrowdown, 7.w, 12.w)
        ]).css(inputBoxCss),
        LDivider(1.w, const Color(0xFFEAEAEA))
      ])
    ]);

    return [
      LSizeBoxHeight(14.w),
      LText(
        title,
        lStyle: itemTitleSty,
      ),
      Stack(
        children: [
          LText(
            StringUtils.defaultValue(item['value'.hx], item['subtitle'.hx]),
            lStyle: inputSty
              ..color = StringUtils.isNotEmpty(item['value'.hx])
                  ? AppColors.textColor
                  : AppColors.textSecondColor,
            onTap: () {},
          ),
          Positioned(
              right: 10.w,
              top: 11.w,
              child: Icon(Icons.keyboard_arrow_down_outlined,
                  color: AppColors.primaryColor, size: 30.w)),
        ],
      ),
    ];
  }

  get itemTitleSty => LStyle(
      // margin-bottom:10px;
      css: '''
font-size: 15px;
font-weight: 400;
color: #333333;''',
      width: double.infinity,
      textAlign: TextAlign.left);

  Widget chooseList({String type = CommKeyDef.credit}) {
    if (authenticationInfo?['items'.hx] == null) return LExpand();
    List<Widget> l = [];
    for (int i = 0; i < authenticationInfo!['items'.hx].length; i++) {
      var item = authenticationInfo!['items'.hx][i];
      if (item['cate'.hx] == CommKeyDef.enum1) {
        l.add(itemSingleSelection(item, type));
      } else if (item['cate'.hx] == CommKeyDef.txt) {
        l.add(itemInput(i, item));
      } else if (item['cate'.hx] == CommKeyDef.citySelect) {
        l.add(itemAddress(item));
      } else if (item['cate'.hx] == CommKeyDef.tip) {
        l.addAll(itemTip(item));
      } else if (item['cate'.hx] == CommKeyDef.day) {
        l.add(itemDate(item));
      } else {
        l.add(itemInput(i, item));
      }
      // l.add(LDivider(1.w, 0xFFECECEC.color));
      l.add(10.lsh);
      if(i == authenticationInfo!['items'.hx].length -1){
        l.add(SizedBox(height: Global.width*.8  ));
      }
    }
    return LContainer(lStyle: LStyle(css: '''
          width:355px;
          padding:8px;
           flex:1;
          '''), child: <Widget>[...l].columnSlid);
  }
}
